<?php
class ItsUsersController extends AppController {
    var $name = 'ItsUsers';

    var $pageTitle = 'User Information';

    var $viewPath = 'its/admins/users';

    var $uses = array('User', 'Customer', 'Site', 'Supplier', 'UserIts', 'UserCustomer', 'UserSupplier', 'UserCoH', 'UserHistory');

    var $helpers = array('Html', 'Form', 'Ajax', 'My');

    var $paginate = array('User' => array('order' => 'User.id DESC'));

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'its_admins');
        $this->set('tabMenu', 'tabmenus/its/admins');

        if ($this->Auth->user('special_user') == false) {
            $this->set('canAdd', false);
            $this->set('canDelete', false);
            $this->set('canSave', false);
        }
    }

    function display() {
        parent::display('User');
        $this->_paging('User', array('username' => 'LIKE', 'name' => 'LIKE', 'surname' => 'LIKE', 'email' => 'LIKE', 'tel' => 'LIKE'));
    }

    function save(){
        $user_id = null;
        if ($this->data) {
            $is_success = false;
            // ฟิลด์ password ที่มี username จะมีการเข้ารหัสอัตโนมัติ
            if(!empty($this->data['User']['password'])){
                if ($this->data['User']['password'] == $this->Auth->password($this->data['User']['password_confirm'])) {
                    $is_success = $this->_save_user();
                } else {
                    $this->User->validationErrors['password'] = 'Password did not match.';
                }
            } else {
                $is_success = $this->_save_user();
            }

            if($is_success) {
                $this->Session->setFlash("Save user succesfull.", 'flash/ok');
                $user_id = $this->User->id;
            } else {
                $this->Session->setFlash("Save user fail.", 'flash/fail');
                $user_id = $this->data['User']['id'];
            }
        }
//        $errors = $this->User->invalidFields();
//        debug($errors);

        $this->data['User']['password'] = '';
        $this->data['User']['password_confirm'] = '';
        $this->setAction('view', $user_id);
    }

     /**
     * เปลี่ยน password
     * @param <type> $user_id
     * @return <type>
     */
    function change_password($user_id) {
        if (!empty($this->data)) {
            $this->User->id = $user_id;
            // old passord ไม่ถูกต้อง
            if ($this->Auth->password($this->data['User']['old_password']) != $this->User->field('password')) {
                $this->Session->setFlash("Please specify password.", 'flash/fail');
                $this->User->validationErrors['old_password'] = 'Password Incorrect.';
                // new password ไม่ตรงกัน
            } elseif ($this->data['User']['new_password'] != $this->data['User']['confirm_new_password'] || empty($this->data['User']['new_password'])) {
                $this->Session->setFlash("Please specify password.", 'flash/fail');
                $this->User->validationErrors['confirm_new_password'] = 'Password did not match.';
            } else {
                $this->User->saveField('password', $this->Auth->password($this->data['User']['new_password']));
                $this->Session->setFlash("Change password succesfull.", 'flash/ok');
                $this->setAction('view', $user_id);
            }
        }
        $this->set('user_id', $user_id);
    }

    private function _save_user() {
        $this->User->create();
        $this->data['User']['collector_id'] = $this->Auth->user('id');
        $this->User->query('BEGIN');
        if($this->User->save($this->data)) {
            $user_id = $this->User->id;
            $userType = $this->data['User']['prefix'];

            // user type จะ save
            $data = null;
            // clas user type ที่จะ save
            $model = null;
            if ($userType == ITS_PREFIX) {
                $this->data['UserIts']['user_id'] = $user_id;
                $data = $this->data['UserIts'];
                $model = $this->UserIts;
            } elseif ($userType == CUST_PREFIX) {
                $this->data['UserCustomer']['user_id'] = $user_id;
                $data = $this->data['UserCustomer'];
                $model = $this->UserCustomer;
            } elseif ($userType == SUPPLIER_PREFIX) {
                $this->data['UserSupplier']['user_id'] = $user_id;
                $data = $this->data['UserSupplier'];
                $model = $this->UserSupplier;
            }
            
            if ($model->save($data)) {
                $this->User->query('COMMIT');
                return true;
            } else {
                $this->User->query('ROLLBACK');
                return false;
            }
        } else {
            $this->User->query('ROLLBACK');
            return false;
        }
    }

    function view($id = null) {
        $this->set('sites', null);
        if ($id != null) {
            $this->data = $this->User->findById($id);
            $this->data['User']['password'] = '';
            $this->data['User']['password_confirm'] = '';
            $userType = $this->data['User']['prefix'];
            if ($userType == ITS_PREFIX) {
                $this->data = array_merge($this->data, $this->UserIts->findByUserId($id));
            } elseif ($userType == CUST_PREFIX) {
                $this->data = array_merge($this->data, $this->UserCustomer->findByUserId($id));
                $this->set('sites', $this->Site->find('list', array('conditions' => array('customer_id' => $this->data['UserCustomer']['customer_id']))));
            } elseif ($userType == SUPPLIER_PREFIX) {
                $this->data = array_merge($this->data, $this->UserSupplier->findByUserId($id));
                
            }
            $this->User->id = $id;
            $this->set('neighbors', $this->User->find('neighbors', array('fields' => array('id', 'name'))));
            
            $this->set('customers', $this->Customer->find('list'));
            $this->set('suppliers', $this->Supplier->find('list', array('order' => 'name')));
            $this->set('mode','edit');
        } else {
            $this->set('mode','add');
            $this->set('customers', $this->Customer->find('list'));
            $this->set('suppliers', $this->Supplier->find('list', array('order' => 'name')));
        }
    }

    function delete($id = null) {
        $is_success = false;
        
        // ถ้ายังไม่เคย login ถึงจะลบได้
        if(!$this->UserHistory->hasAny(array('user_id' => $id))) {
            // ลบข้อมูล ตาม user type
            $this->User->id = $id;
            $prefix = $this->User->field('prefix');
            if ($prefix == User::USER_PREFIX_SUPPLIER) {
                $us = $this->UserSupplier->findByUserId($id);
                $this->UserSupplier->delete($us['UserSupplier']['id']);
            } elseif ($prefix == User::USER_PREFIX_CUSTOMER) {
                $uc = $this->UserCustomer->findByUserId($id);
                $this->UserCustomer->delete($uc['UserCustomer']['id']);
            } elseif ($prefix == User::USER_PREFIX_ITS) {
                $ui = $this->UserIts->findByUserId($id);
                $this->UserIts->delete($ui['UserIts']['id']);
            }
            $is_success = $this->User->delete($id);
        }
        if ($is_success) {
            $this->Session->setFlash("User delete succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("User delete fail.", 'flash/fail');
        }
        $this->setAction('display');
    }

    function popup_search() {
        parent::popup_search();

    }

    /**
     * action สำหรับ แสดง Customer on Hand ที่ user นี้จะดูข้อมูลได้
     * @param int $user_id
     */
    function customer_on_hand_view($user_id) {
        $this->layout = 'ajax';
        $this->UserCoH->contain('Customer');

        // Subquery ดึงรายการ Customer ที่ไม่อยู่ใน Customer Contract list ของ Supplier นี้
        $conditionsSubQuery['UserCoH.user_id'] = $user_id;
        $dbo = $this->UserCoH->getDataSource();
        $subQuery = $dbo->buildStatement(
            array(
            'fields' => array('UserCoH.customer_id'),
            'table' => $dbo->fullTableName($this->UserCoH),
            'alias' => 'UserCoH',
            'conditions' => $conditionsSubQuery,
            'order' => null, 'limit' => null, 'group' => null,
            ),
            $this->UserCoH
        );
        $subQuery = ' Customer.id NOT IN (' . $subQuery . ') ';
        $subQueryExpression = $dbo->expression($subQuery);
        $conditions[] = $subQueryExpression;

        $customers = $this->Customer->find('list', compact('conditions'));
        $this->set('customers', $customers);

        $this->data = $this->UserCoH->findAllByUserId($user_id);
        $this->set('user_id', $user_id);
    }

    /**
     * บันทึก Customer เข้าไปใน Contract list ของ Supplier
     */
    function save_customer_on_hand() {
        $this->layout = 'ajax';
        $user_id = $this->data['UserCoH']['user_id'];
        $this->UserCoH->query("BEGIN");;
        $this->data['UserCoH']['collector_id'] = $this->Auth->user('id');
        if($this->UserCoH->save($this->data)) {
            $this->UserCoH->query("COMMIT");;
            $this->Session->setFlash("Add Customer to customer on hand for this user succesfull.", 'flash/ok');
        } else {
            $this->UserCoH->query("ROLLBACK");
            $this->Session->setFlash("Cannot add this customer to customer on hand list.", 'flash/fail');
        }
        $this->setAction('customer_on_hand_view', $user_id);
    }

    /**
     * ลบ Customer ออกจาก Customer on hand ของ User
     * @param <type> $id
     */
    function delete_contract($id) {
        $this->layout = 'ajax';
        $is_success = false;

        // ลบ รายการ
        $this->UserCoH->id = $id;
        $user_id = $this->UserCoH->field('user_id');
        $is_success = $this->UserCoH->delete($id);

        if ($is_success) {
            $this->Session->setFlash("Delete customer from customer on hand list succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Can not delete this customer.", 'flash/fail');
        }
        $this->setAction('customer_on_hand_view', $user_id);
    }
}
?>